import 'dart:io';
import 'package:barrage/hi_barrage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bilibili/barrage/barrage_input.dart';
import 'package:flutter_bilibili/barrage/barrage_switch.dart';
import 'package:flutter_bilibili/util/hi_constants.dart';
import 'package:yeyu_net/core/hi_error.dart';
import 'package:flutter_bilibili/http/dao/favorite_dao.dart';
import 'package:flutter_bilibili/http/dao/like_dao.dart';
import 'package:flutter_bilibili/http/dao/video_detail_dao.dart';
import 'package:flutter_bilibili/model/video_detail_mo.dart';
import 'package:flutter_bilibili/model/video_model.dart';
import 'package:flutter_bilibili/provider/theme_provider.dart';
import 'package:flutter_bilibili/util/toast.dart';
import 'package:flutter_bilibili/util/view_util.dart';
import 'package:flutter_bilibili/widget/appbar.dart';
import 'package:flutter_bilibili/widget/expandable_content.dart';
import 'package:flutter_bilibili/widget/hi_tab.dart';
import 'package:flutter_bilibili/widget/navigation_bar.dart';
import 'package:flutter_bilibili/widget/video_header.dart';
import 'package:flutter_bilibili/widget/video_large_card.dart';
import 'package:flutter_bilibili/widget/video_toolbar.dart';
import 'package:flutter_bilibili/widget/video_view.dart';
import 'package:flutter_overlay/flutter_overlay.dart';
import 'package:provider/provider.dart';

class VideoDetailPage extends StatefulWidget {
  final VideoModel videoModel;

  const VideoDetailPage(this.videoModel);
  @override
  _VideoDetailPageState createState() => _VideoDetailPageState();
}

class _VideoDetailPageState extends State<VideoDetailPage>
    with TickerProviderStateMixin {
  TabController _controller;
  List tabs = ['简介', '评论'];
  VideoDetailMo videoDetailMo;
  VideoModel videroModel;
  List<VideoModel> videoList = [];
  var _barrageKey = GlobalKey<HiBarrageState>();
  bool _inoutShowing = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    changeStatusBar(
        color: Colors.black, statusStyle: StatusStyle.LIGHT_CONTENT);
    _controller = TabController(length: tabs.length, vsync: this);
    videroModel = widget.videoModel;
    _loadDetail();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MediaQuery.removePadding(
          context: context,
          removeTop: Platform.isIOS,
          child: videroModel.url != null
              ? Column(
                  children: [
                    NavigationBar(
                      color: Colors.black,
                      statusStyle: StatusStyle.LIGHT_CONTENT,
                      height: Platform.isAndroid ? 0 : 46,
                    ),
                    _buildVideoView(),
                    _huildTabNavigator(),
                    Flexible(
                        child: TabBarView(controller: _controller, children: [
                      _buildDetailList(),
                      Container(
                        child: Text(''),
                      )
                    ]))
                  ],
                )
              : Container()),
    );
  }

  _buildVideoView() {
    var model = videroModel;
    return VideoView(
      url: model.url,
      cover: model.cover,
      overlayUI: videoAppBar(),
      barrageUI: HiBarrage(
        key: _barrageKey,
        vid: model.vid,
        autoPlay: true,
        headers: HiConstants.headers(),
      ),
    );
  }

  _huildTabNavigator() {
    var themeMode = context.read<ThemeProvider>();
    return Material(
      elevation: 5,
      shadowColor: Colors.grey[100],
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.only(left: 20),
        height: 39,
        color: themeMode.isDark() ? Colors.black : Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [_tabBar(), _buildBarrageBtn()],
        ),
      ),
    );
  }

  _tabBar() {
    return HiTab(
      tabs: tabs.map<Tab>((name) {
        return Tab(
          text: name,
        );
      }).toList(),
      controller: _controller,
    );
  }

  _buildDetailList() {
    return ListView(
      padding: EdgeInsets.all(0),
      children: [...buildContents(), ..._buildVideoList()],
    );
  }

  buildContents() {
    return [
      VideoHeader(
        owner: videroModel.owner,
      ),
      ExpandableContent(mo: videroModel),
      VideoToolBar(
          detailMo: videoDetailMo,
          videoModel: videroModel,
          onLike: _doLike,
          onCoin: _onCoin,
          onUnLike: _onUnLike,
          onFavorite: _onFavorite,
          onShare: _onShare)
    ];
  }

  void _loadDetail() async {
    try {
      VideoDetailMo result = await VideoDetailDao.get(videroModel.vid);
      setState(() {
        videoDetailMo = result;
        videroModel = result.videoInfo;
        videoList = result.videoList;
      });
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print(e);
    }
  }

  void _doLike() async {
    try {
      var result = await LikeDao.like(videroModel.vid, !videoDetailMo.isLike);
      videoDetailMo.isLike = !videoDetailMo.isLike;
      if (videoDetailMo.isLike) {
        videroModel.like += 1;
      } else {
        videroModel.like -= 1;
      }
      setState(() {
        videoDetailMo = videoDetailMo;
        videroModel = videroModel;
      });
      showToast(result['msg']);
    } on NeedAuth catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    }
  }

  void _onCoin() {}

  void _onFavorite() async {
    try {
      var result = await FavoriteDao.favorite(
          videroModel.vid, !videoDetailMo.isFavorite);
      videoDetailMo.isFavorite = !videoDetailMo.isFavorite;
      if (videoDetailMo.isFavorite) {
        videroModel.favorite += 1;
      } else {
        videroModel.favorite -= 1;
      }
      setState(() {
        videoDetailMo = videoDetailMo;
        videroModel = videroModel;
      });
      showToast(result['msg']);
    } on NeedAuth catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    }
  }

  void _onShare() {}

  void _onUnLike() {}

  _buildVideoList() {
    return videoList
        .map((VideoModel mo) => VideoLargeCard(videoModel: mo))
        .toList();
  }

  _buildBarrageBtn() {
    return BarrageSwitch(
      inoutShowing: _inoutShowing,
      onShowInput: () {
        setState(() {
          _inoutShowing = true;
        });
        HiOverlay.show(context, child: BarrageInput(onTabClose: () {
          setState(() {
            _inoutShowing = false;
          });
        })).then((value) => {_barrageKey.currentState.send(value)});
      },
      onBarrageSwitch: (open) {
        if (open) {
          _barrageKey.currentState.play();
        } else {
          _barrageKey.currentState.pause();
        }
      },
    );
  }
}
